using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace CourseSync.LibFetcher.Filter
{
    public class BoundFilter : Filter
    {
        protected Regex m_Prefix;
        protected Regex m_Postfix;
        protected Regex m_Filter;

        public BoundFilter(Regex filter)
            : this(null, null, filter)
        {
        }

        public BoundFilter(string filter)
            : this(null, null, new Regex(filter, RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.IgnoreCase))
        {
        }

        public BoundFilter(string filter, RegexOptions options)
            : this(null, null, new Regex(filter, options))
        {
        }

        public BoundFilter(string prefix, string postfix, string filter)
            : this((prefix == null) ? null : new Regex(prefix, RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.IgnoreCase),
                   (postfix == null) ? null : new Regex(postfix, RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.IgnoreCase),
                   (filter == null) ? null : new Regex(filter, RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.IgnoreCase))
        {
        }

        public BoundFilter(Regex prefix, Regex postfix, Regex filter)
        {
            m_Prefix = prefix;
            m_Postfix = postfix;
            m_Filter = filter;
        }

        public override MatchCollection GetMatches(string content)
        {
            try
            {
                int start_position;
                int end_position;
                if (m_Prefix != null)
                {
                    Match prefix = m_Prefix.Match(content);
                    if (!prefix.Success)
                        return null;
                    start_position = prefix.Index + prefix.Length;
                }
                else
                    start_position = 0;

                if (m_Postfix != null)
                {
                    Match postfix = m_Postfix.Match(content, start_position);
                    if (!postfix.Success)
                        return null;
                    end_position = postfix.Index;
                }
                else
                    end_position = content.Length;

                if ((start_position != 0) || (end_position != content.Length))
                    content = content.Substring(start_position, end_position - start_position);

                return m_Filter.Matches(content);
            }
            catch (NullReferenceException)
            {
                return null;
            }
        }
    }
}
